package com.movecar.ui;

import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager;

import com.alipay.android.app.sdk.AliPay;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movecar.R;
import com.movecar.adapter.ImagePagerAdapter;
import com.movecar.alipay.Keys;
import com.movecar.alipay.Result;
import com.movecar.alipay.Rsa;
import com.movecar.model.PayRmbBean;
import com.movecar.model.Pictures;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.ListUtils;
import com.movecar.utils.RequestResultCallback;
import com.movecar.widget.CustomProgressDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 活动详情-支付
 * 
 * @author Zhao.JQ
 * 
 */
public class GroupDetailPaymentActivity extends Activity implements OnClickListener {

	private CustomProgressDialog progressDialog = null;
	private TextView group_name, price, beans, cash, explain;
	private AutoScrollViewPager group_img;
	private ImageLoader imageLoader = null;
	private PayRmbBean mPayRmbBean;
	private String messageId;
	private LinearLayout main_linear;
	private String out_trade_no;
	public static final String TAG = "alipay-sdk";

	private static final int RQF_PAY = 1;

	private static final int RQF_LOGIN = 2;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.group_detail_payment);
		imageLoader = ImageLoader.getInstance();
		messageId = getIntent().getStringExtra("messageId");
		initView();
	}
	

	private void initView() {
		main_linear = (LinearLayout) findViewById(R.id.main_linear);
		group_img = (AutoScrollViewPager) findViewById(R.id.group_img);
		group_name = (TextView) findViewById(R.id.group_name);
		price = (TextView) findViewById(R.id.price);
		beans = (TextView) findViewById(R.id.beans);
		cash = (TextView) findViewById(R.id.cash);
		explain = (TextView) findViewById(R.id.explain);
		Button back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		findViewById(R.id.btn_pay).setOnClickListener(this);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("支付");
		startProgressDialog();
		signinPayRmb();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_left:

			finish();

			break;
		case R.id.btn_pay:
			if ("0.0".equals(String.valueOf((Double.parseDouble(mPayRmbBean.getJoinRmb()))))) {
				Intent next = new Intent();
				next.putExtra("coin", String.valueOf((int) ((Double.parseDouble(mPayRmbBean.getJoinCoin())))));
				next.putExtra("rmb", "0");
				next.putExtra("payCode", "");
				next.putExtra("messageId", messageId);
				setResult(RESULT_OK, next);
				finish();
			} else {
				pay();
			}
			break;

		default:
			break;
		}

	}

	/**
	 * 异步调取支付接口
	 */
	private void pay() {
		try {
			Log.i("GroupDetailPaymentActivity", "pay");
			String info = getNewOrderInfo();

			String sign = Rsa.sign(info, Keys.PRIVATE);
			sign = URLEncoder.encode(sign);
			info += "&sign=\"" + sign + "\"&" + getSignType();
			Log.i("ExternalPartner", "start pay");
			// start the pay.
			Log.i(TAG, "info = " + info);

			final String orderInfo = info;
			new Thread() {
				public void run() {
					AliPay alipay = new AliPay(GroupDetailPaymentActivity.this, mHandler);

					// 设置为沙箱模式，不设置默认为线上环境
					// alipay.setSandBox(true);

					String result = alipay.pay(orderInfo);

					Log.i(TAG, "result = " + result);
					Message msg = new Message();
					msg.what = RQF_PAY;
					msg.obj = result;
					mHandler.sendMessage(msg);
				}
			}.start();

		} catch (Exception ex) {
			ex.printStackTrace();
			Alert.error(GroupDetailPaymentActivity.this, "Failure calling remote service");
		}
	}

	private String getNewOrderInfo() {
		StringBuilder sb = new StringBuilder();
		sb.append("partner=\"");
		sb.append(Keys.DEFAULT_PARTNER);

		sb.append("\"&out_trade_no=\"");

		sb.append(getOutTradeNo());
		sb.append("\"&subject=\"");
		sb.append(mPayRmbBean.getExchangeTitle());// 订单标题
		sb.append("\"&body=\"");
		sb.append(mPayRmbBean.getExchangeContent());// 商品详情
		sb.append("\"&total_fee=\"");
		sb.append(cash.getText().toString().substring(8, cash.getText().length() - 1));// 总金额

		sb.append("\"&service=\"mobile.securitypay.pay");
		sb.append("\"&_input_charset=\"UTF-8");
		sb.append("\"&return_url=\"");
		sb.append(URLEncoder.encode("http://m.alipay.com"));
		sb.append("\"&payment_type=\"1");
		sb.append("\"&seller_id=\"");
		sb.append(Keys.DEFAULT_SELLER);

		// 如果show_url值为空，可不传
		// sb.append("\"&show_url=\"");
		sb.append("\"&it_b_pay=\"1m");
		sb.append("\"");

		return new String(sb);
	}

	private String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
		Date date = new Date();
		String key = format.format(date);

		java.util.Random r = new java.util.Random();
		key += r.nextInt();
		key = key.substring(0, 15);
		Log.d(TAG, "outTradeNo: " + key);
		out_trade_no = key;
		return key;
	}

	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Result result = new Result((String) msg.obj);

			switch (msg.what) {
			case RQF_PAY:
				Alert.info(GroupDetailPaymentActivity.this, result.getResultStatus());
				if ("支付成功".equals(result.getResultStatus())) {
					Intent intent = new Intent();
					intent.putExtra(
							"coin",
							String.valueOf((int) (Double.parseDouble(beans.getText().toString()
									.substring(6, beans.getText().length() - 1)))));
					intent.putExtra("rmb", cash.getText().toString().substring(8, cash.getText().length() - 1));
					intent.putExtra("payCode", out_trade_no);
					intent.putExtra("messageId", messageId);
					setResult(RESULT_OK, intent);
					finish();
				}
				break;
			case RQF_LOGIN: {
				Alert.error(GroupDetailPaymentActivity.this, result.getResultStatus());

			}
				break;
			default:
				break;
			}
		};
	};

	/**
	 * 获取页面信息
	 */
	@SuppressWarnings("unchecked")
	private void signinPayRmb() {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "signinPayRmbNew1"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("messageId", messageId));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mPayRmbBean = gson.fromJson(result, PayRmbBean.class);
				} catch (Exception e) {
					return;
				}

				if (mPayRmbBean != null) {
					main_linear.setVisibility(View.VISIBLE);
					group_name.setText(mPayRmbBean.getMsgTitle());
					price.setText("价格： " + mPayRmbBean.getJoinRmb() + "元");
					beans.setText("需要云豆： " + mPayRmbBean.getJoinCoin());
					cash.setText("需要支付现金： " + mPayRmbBean.getJoinRmb() + "元");
					explain.setText(mPayRmbBean.getReturnMsg());
					Type type = new TypeToken<List<PayRmbBean>>() {
					}.getType();
					Gson gson1 = new Gson();
					Object fromJson = gson1.fromJson(mPayRmbBean.getMpArr(), type);
					ArrayList<PayRmbBean> mDataList = null;
					try {
						mDataList = (ArrayList<PayRmbBean>) fromJson;
					} catch (Exception e) {
						return;
					}
					List<Pictures> imageList = new ArrayList<Pictures>();
					if (mDataList != null) {

						for (PayRmbBean bean : mDataList) {
							Pictures p = new Pictures();
							p.setUrl(bean.getUrl());
							imageList.add(p);
						}

					}
					group_img.setAdapter(new ImagePagerAdapter(GroupDetailPaymentActivity.this, imageList)
							.setInfiniteLoop(false));
					group_img.setOnPageChangeListener(new MyOnPageChangeListener());

					group_img.setInterval(2000);
					group_img.startAutoScroll();
					group_img.setCycle(true);
					group_img.setCurrentItem(Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2
							% ListUtils.getSize(imageList));

				} else {
					Alert.error(GroupDetailPaymentActivity.this, "系统异常");
				}

			}

			@Override
			public void onFail(String exception) {
				Alert.error(GroupDetailPaymentActivity.this, "与服务器连接失败，请检查网络");

			}
		}, DataStore.class, AppConfig.GROUP).execute(params);
	}

	public class MyOnPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageSelected(int position) {
			// indexText.setText(new StringBuilder().append((position) %
			// ListUtils.getSize(imageUrlList) + 1).append("/")
			// .append(ListUtils.getSize(imageUrlList)));
		}

		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
}